package cn.mulanbay.log.web.controller;

import cn.mulanbay.api.system.bean.RemoteOperationLog;
import cn.mulanbay.common.bean.ResultBean;
import cn.mulanbay.common.util.BeanCopy;
import cn.mulanbay.common.util.DateUtil;
import cn.mulanbay.common.util.IPAddressUtil;
import cn.mulanbay.common.util.StringUtil;
import cn.mulanbay.log.handler.LogHandler;
import cn.mulanbay.log.persistent.service.OperationLogService;
import cn.mulanbay.log.web.bean.request.operationLog.OperationLogSearch;
import cn.mulanbay.log.web.bean.response.systemLog.OperationBeanDetailVo;
import cn.mulanbay.persistent.entity.OperationLog;
import cn.mulanbay.persistent.entity.User;
import cn.mulanbay.persistent.enums.IdFieldType;
import cn.mulanbay.web.controller.BaseController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.io.Serializable;
import java.time.LocalDateTime;

/**
 * 操作日志
 *
 * @author fenghong
 * @create 2022-01-16 10:00
 */
@RestController
@RequestMapping("/operationLog")
public class OperationLogController extends BaseController {

    @Autowired
    OperationLogService operationLogService;

    @Autowired
    LogHandler logHandler;

    /**
     * 获取列表数据
     *
     * @return
     */
    @RequestMapping(value = "/getData", method = RequestMethod.GET)
    public ResultBean getData(OperationLogSearch sf) {
        return callbackDataGrid(operationLogService.getDataList(sf));
    }

    /**
     * 创建
     *
     * @return
     */
    @RequestMapping(value = "/create", method = RequestMethod.POST)
    public ResultBean create(@RequestBody @Valid RemoteOperationLog sl) {
        OperationLog log = new OperationLog();
        BeanCopy.copyProperties(sl,log);
        log.setStoreTime(LocalDateTime.now());
        log.setCreatedTime(LocalDateTime.now());
        log.setStoreDuration(DateUtil.getDurationMills(log.getOccurEndTime(),log.getStoreTime()));
        log.setHandleDuration(DateUtil.getDurationMills(log.getOccurStartTime(),log.getOccurEndTime()));
        Long userId = log.getUserId();
        if(userId==null){
            log.setUserId(0L);
            log.setUsername("系统用户");
        }else{
            if(StringUtil.isEmpty(log.getUsername())){
                User user = logHandler.getUser(userId);
                if(user!=null){
                    log.setUsername(user.getUsername());
                }else{
                    log.setUsername(userId.toString());
                }
            }
        }
        log.setHostIpAddress(IPAddressUtil.getLocalIpAddress());
        operationLogService.save(log);
        return callback(null);
    }

    /**
     * 获取请求参数
     *
     * @return
     */
    @RequestMapping(value = "/getParas", method = RequestMethod.GET)
    public ResultBean getParas(Long id) {
        OperationLog br = operationLogService.getById(id);
        return callback(br.getParas());
    }

    /**
     * 获取返回数据
     *
     * @return
     */
    @RequestMapping(value = "/getReturnData", method = RequestMethod.GET)
    public ResultBean getReturnData(Long id) {
        OperationLog br = operationLogService.getById(id);
        return callback(br.getReturnData());
    }

    /**
     * 查询被操作的业务对象的数据
     *
     * @param id 为操作日志的记录号
     * @return
     */
    @RequestMapping(value = "/getBeanDetail", method = RequestMethod.GET)
    public ResultBean getBeanDetail(Long id) {
        OperationLog br = operationLogService.getById(id);
        String idValue = br.getIdValue();
        if (StringUtil.isEmpty(idValue)) {
            return callbackErrorInfo("没有操针对象主键信息");
        } else {
            OperationBeanDetailVo response = new OperationBeanDetailVo();
            response.setIdValue(idValue);
//            response.setBeanName(br.getSystemFunction().getBeanName());
//            Serializable bussId = formatIdValue(br.getSystemFunction().getIdFieldType(), idValue);
//            String idFiled = this.formatIdField(br.getSystemFunction().getIdField());
//            Object o = baseService.getObject(br.getSystemFunction().getBeanName(), bussId, idFiled);
//            response.setBeanData(o);
            return callback(response);
        }
    }

    /**
     * 删除操作因为支持多个，索引会多加了s，实际上字段是id
     * @param idField
     * @return
     */
    private String formatIdField(String idField) {
        if("ids".equals(idField)){
            return "id";
        }
        return idField;
    }

    private Serializable formatIdValue(IdFieldType idFieldType, String idValue) {
        Serializable bussId = null;
        if (idFieldType == IdFieldType.LONG) {
            bussId = Long.valueOf(idValue);
        } else if (idFieldType == IdFieldType.INTEGER) {
            bussId = Integer.valueOf(idValue);
        } else if (idFieldType == IdFieldType.SHORT) {
            bussId = Short.valueOf(idValue);
        } else {
            bussId = idValue;
        }
        return bussId;
    }
}
